/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.func;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.auth.check.annotation.AuthCheckDataPermission;
import com.je.auth.check.annotation.CheckDataType;
import com.je.common.base.DynaBean;
import com.je.common.base.func.funcPerm.fastAuth.CustomerFuncPerm;
import com.je.common.base.func.funcPerm.fastAuth.FuncQuickPermission;
import com.je.common.base.func.funcPerm.roleSqlAuth.RoleSqlAuthVo;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.MessageUtils;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.func.CustomerFuncPermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 自定义数据权限配置
 */
@RestController
@RequestMapping(value = "/je/meta/customer/funcPerm")
public class CustomerFuncPermSettingController extends AbstractPlatformController {

    @Autowired
    private CustomerFuncPermService customerFuncPermService;

    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @AuthCheckDataPermission(checkDataType = CheckDataType.UPDATE)
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        String code = param.getParameter("PERM_CODE");
        List<DynaBean> list = metaService.select("JE_CORE_FUNCINFO", ConditionsWrapper.builder().eq("FUNCINFO_FUNCCODE", code));
        if (list.size() > 0) {
            return BaseRespResult.errorResult("自定义编码和系统功能中的重复，请检查！");
        }
        return BaseRespResult.successResult(manager.doSave(param, request).getValues());
    }

    @Override
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @AuthCheckDataPermission(checkDataType = CheckDataType.UPDATE)
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        //检验数据
        String data = param.getStrData();
        String message = checkData(data);
        if (!Strings.isNullOrEmpty(message)) {
            return BaseRespResult.errorResult(message);
        }
        return super.doUpdateList(param, request);
    }

    private String checkData(String data) {
        String message = "";
        JSONArray jsonArray = JSONArray.parseArray(data);
        for (int i = 0; i < jsonArray.size(); i++) {
            if (!Strings.isNullOrEmpty(message)) {
                break;
            }
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String pkValue = jsonObject.getString("JE_CORE_CUSTOMER_PERM_FUNC_ID");
            String code = jsonObject.getString("FUNC_CODE");
            ConditionsWrapper conditionsWrapper = ConditionsWrapper.builder().eq("FUNC_CODE", code);
            if (!Strings.isNullOrEmpty(pkValue)) {
                conditionsWrapper.ne("JE_CORE_CUSTOMER_PERM_FUNC_ID", pkValue);
            }
            int funcSize = metaService.select("JE_CORE_CUSTOMER_PERM_FUNC", conditionsWrapper).size();
            if (funcSize > 0) {
                message = String.format("%s编码重复，请检查！", code);
            }
            List<DynaBean> list = metaService.select("JE_CORE_FUNCINFO",
                    ConditionsWrapper.builder().eq("FUNCINFO_FUNCCODE", code));
            if (list.size() > 0) {
                message = String.format("自定义编码%s和系统功能中的重复，请检查！", code);
            }
        }
        return message;
    }

    /**
     * 保存权限
     */
    @RequestMapping(value = "/doSavePerm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult doSavePerm(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        dynaBean.setStr("type", getStringParameter(request, "type"));
        customerFuncPermService.doUpdatePerm(dynaBean);
        return BaseRespResult.successResult(MessageUtils.getMessage("common.save.success"));
    }

    /**
     * 获取数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getPermData", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getPermData(HttpServletRequest request) {
        Boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String type = getStringParameter(request, "type");
        dynaBean.setStr("type", type);
        dynaBean.set("en", en);
        List<DynaBean> fastAuthList = customerFuncPermService.getPermData(dynaBean);
        return BaseRespResult.successResult(fastAuthList);
    }

    /**
     * 清空数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/restoreDefault", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult restoreDefault(HttpServletRequest request) {
        String funcCode = getStringParameter(request, "funcCode");
        customerFuncPermService.restoreDefault(funcCode);
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

    /**
     * 获取快速授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCustomerFuncQuickPermission", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public FuncQuickPermission getCustomerFuncQuickPermission(HttpServletRequest request) {
        String code = getStringParameter(request, "code");
        FuncQuickPermission funcQuickPermission = customerFuncPermService.getCustomerFuncQuickPermission(code);
        return funcQuickPermission;
    }


    /**
     * 获取角色sql授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCustomerFuncRoleSqlPermission", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public RoleSqlAuthVo getCustomerFuncRoleSqlPermission(HttpServletRequest request) {
        String code = getStringParameter(request, "code");
        RoleSqlAuthVo roleSqlAuthVo = customerFuncPermService.getCustomerFuncRoleSqlPermission(code);
        return roleSqlAuthVo;
    }

    /**
     * 获取sql授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCustomerFuncSqlPermission", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getCustomerFuncSqlPermission(HttpServletRequest request) {
        String code = getStringParameter(request, "code");
        String sql = customerFuncPermService.getCustomerFuncSqlPermission(code);
        return sql;
    }

    /**
     * 获取快速授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCustomerFuncAllPermission", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public CustomerFuncPerm getCustomerFuncAllPermission(HttpServletRequest request) {
        String code = getStringParameter(request, "code");
        FuncQuickPermission funcQuickPermission = customerFuncPermService.getCustomerFuncQuickPermission(code);
        RoleSqlAuthVo roleSqlAuthVo = customerFuncPermService.getCustomerFuncRoleSqlPermission(code);
        String sql = customerFuncPermService.getCustomerFuncSqlPermission(code);
        CustomerFuncPerm customerFuncPerm = new CustomerFuncPerm();
        customerFuncPerm.setFuncQuickPermission(funcQuickPermission);
        customerFuncPerm.setRoleSqlAuthVo(roleSqlAuthVo);
        customerFuncPerm.setSql(sql);
        return customerFuncPerm;
    }

    @RequestMapping(value = "/buildCustomerFuncPermSql", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String buildCustomerFuncPermSql(HttpServletRequest request) {
        String code = getStringParameter(request, "code");
        String createUserIdField = getStringParameter(request, "createUserIdField");
        String createDeptIdField = getStringParameter(request, "createDeptIdField");
        String companyIdFieldCode = getStringParameter(request, "companyIdFieldCode");
        String groupCompanyIdFieldCode = getStringParameter(request, "groupCompanyIdFieldCode");
        FuncQuickPermission funcQuickPermission = customerFuncPermService.getCustomerFuncQuickPermission(code);
        funcQuickPermission.setCreateUserIdField(createUserIdField);
        funcQuickPermission.setCreateDeptIdField(createDeptIdField);
        funcQuickPermission.setCompanyIdFieldCode(companyIdFieldCode);
        funcQuickPermission.setGroupCompanyIdFieldCode(groupCompanyIdFieldCode);
        RoleSqlAuthVo roleSqlAuthVo = customerFuncPermService.getCustomerFuncRoleSqlPermission(code);
        String sql = customerFuncPermService.getCustomerFuncSqlPermission(code);
        CustomerFuncPerm customerFuncPerm = new CustomerFuncPerm();
        customerFuncPerm.setFuncQuickPermission(funcQuickPermission);
        customerFuncPerm.setRoleSqlAuthVo(roleSqlAuthVo);
        customerFuncPerm.setSql(sql);
        return customerFuncPermService.buildCustomerFuncPermSql(customerFuncPerm);
    }


}
